﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Magiq.Insert;
using Magiq.Query;

namespace Magiq.Databases.Query
{
    public class InsertSourceDatabaseEnumerableStrategy<T, TChild> : IEnumerableStrategy<TChild>, IDatabaseBasedExecution
    {
        private readonly InsertSource<TChild> source;

        public InsertSourceDatabaseEnumerableStrategy(IOrmAdapter ormAdapter, InsertSource<TChild> source)
        {
            OrmAdapter = ormAdapter;
            this.source = source;
        }

        #region IDatabaseBasedExecution Members

        public IOrmAdapter OrmAdapter { get; private set; }

        #endregion

        public IEnumerable<TChild> Execute()
        {
            var items = OrmAdapter.GetSourceQueryableFrom<T,TChild>(source);
            var @new = ((Expression<Func<T, TChild>>) source.InsertExpression).Compile();
            return items.ToArray().Select(@new);
        }
    }
}